#!/bin/bash

# InfluxDB初始化脚本
# RedFire Trading System - InfluxDB 2.x Setup Script

set -e

echo "=================================================="
echo "RedFire InfluxDB初始化开始..."
echo "Time: $(date)"
echo "=================================================="

# 等待InfluxDB启动
echo "等待InfluxDB服务启动..."
until curl -f http://localhost:8086/health 2>/dev/null; do
    echo "等待InfluxDB启动中..."
    sleep 2
done

echo "InfluxDB服务已启动"

# 检查是否已经设置过
if curl -s http://localhost:8086/api/v2/setup | grep -q "true"; then
    echo "InfluxDB已经初始化完成"
    exit 0
fi

# 执行初始化设置
echo "开始InfluxDB初始化设置..."

# 设置管理员用户和组织
curl -X POST http://localhost:8086/api/v2/setup \
  -H "Content-Type: application/json" \
  -d '{
    "username": "redfire_admin",
    "password": "redfire_influx_2025",
    "org": "redfire_org",
    "bucket": "redfire_bucket",
    "retentionPeriodSeconds": 2592000
  }'

echo "InfluxDB初始化设置完成"

# 创建额外的buckets
echo "创建额外的数据桶..."

# 获取认证token (这里需要从setup响应中获取，或者使用预设的token)
# 实际部署时需要配置正确的token获取方式

echo "=================================================="
echo "InfluxDB初始化完成!"
echo "访问地址: http://localhost:8086"
echo "用户名: redfire_admin"
echo "组织: redfire_org"
echo "默认bucket: redfire_bucket"
echo "=================================================="
